//
//  LoaddingButton.swift
//  koolcar
//
//  Created by xiantian on 2023/9/28.
//

import UIKit

class LoaddingButton: UIButton {
    private var originalButtonText: String?
    private var activityIndicator: UIActivityIndicatorView = {
        let tempView = UIActivityIndicatorView()
        tempView.hidesWhenStopped = true
        tempView.color = .white
        return tempView
    }()
    
    func showLoading() {
        originalButtonText = self.titleLabel?.text
        self.setTitle("", for: .normal)
        showSpinning()
    }
    
    func handleLoadding() {
        self.setup_titleLabel(text: self.originalButtonText ?? "")
        self.activityIndicator.stopAnimating()
    }
    
    
//    private func createActivityIndicator() -> UIActivityIndicatorView {
//        let activityIndicator = UIActivityIndicatorView()
//        activityIndicator.hidesWhenStopped = true
//        activityIndicator.color = .white
//        return activityIndicator
//    }
//
    private func showSpinning() {
        activityIndicator.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(activityIndicator)
        centerActivityIndicatorInButton()
        activityIndicator.startAnimating()
    }
    
    private func centerActivityIndicatorInButton() {
        let xCenterConstraint = NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: activityIndicator, attribute: .centerX, multiplier: 1, constant: 0)
        self.addConstraint(xCenterConstraint)
        
        let yCenterConstraint = NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: activityIndicator, attribute: .centerY, multiplier: 1, constant: 0)
        self.addConstraint(yCenterConstraint)
    }
    
}
